package hmh.threadpooldemo.service.impl;

import com.google.common.collect.Lists;
import hmh.threadpooldemo.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {

    //导入线程池
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    public void hello() {
        System.out.println("say hello");
        System.out.println("hh");
    }

    @Override
    public void executeTask() {
        //存放数据的集合
        ArrayList<String> list = new ArrayList<>();
        //从数据中获取数据
        getData(list);
        //将集合进行分组，1000条为一组，将每一组分给不同的线程池
        List<List<String>> partition = Lists.partition(list, 1000);

        List<CompletableFuture<List<String>>> futures = partition.stream().map(sublist -> CompletableFuture.supplyAsync(() -> getResult(sublist), taskExecutor))
                .collect(Collectors.toList());

        List<String> result = futures.stream().map(CompletableFuture::join).flatMap(List::stream).collect(Collectors.toList());

        System.out.println(result);

    }

    private List<String> getResult(List<String> strings) {
        return strings.stream()
                .filter(s -> Integer.parseInt(s) % 2 == 0)
                .collect(Collectors.toList());
    }

    //创建出10万条数据
    private void getData(List<String> list) {
        for (int i = 1; i <=100000; i++) {
            list.add(i+"");
        }
    }


}
